import requests as requests
from lxml import etree
import base64

def download(src, id):

    try:
        if src.startswith('data'):
            #base64数据格式  data:image/png;base64
            index = src.index("/")
            suffix = src[index+1:index+4] +"."
            dir = './' + str(id) + suffix
            request_base64='''   '''
            imgdata = base64.b64decode(request_base64)
            with open(dir, 'wb') as fh:
                fh.write(imgdata)
        else:
            suffix = src[src.rindex("."):len(src)]
            dir = './' + str(id) + suffix
            pic = requests.get(src, timeout=10)
            fp = open(dir, 'wb')
            fp.write(pic.content)
            fp.close()

    except requests.exceptions.ConnectionError:
            print('图片无法下载')

if __name__ == '__main__':

    url = 'https://image.baidu.com/'
    html = requests.get(url).text
    # 得到返回结果
    response = etree.HTML(html)

    results = response.xpath('//img/@src')

    i = 0
    for url in results:
        if  url:
            print(url)  # 查看当前下载的图片网址
            download(url, i )  # 下载一张图片
            i+=1


